//
//  BatchUploadVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/11/14.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "BatchUploadVC.h"
#import "IWTextView.h"
#import "IGOSSManager.h"
#import "IGIssueImageCell.h"
#import "IGIssueDelImageViewController.h"
#import "IGUpProductionApi.h"
#import "ArtGalleryViewController.h"
#import "IGCircleprogress.h"

#define nameTag             511//作品名
#define contextTag          512//作品详情
static CGFloat lineSpaceWidthImage = 6;

@interface BatchUploadVC ()<UITableViewDataSource, UITableViewDelegate,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
{
    NSString *publicName;   //  作品名
    NSString *publicContext;  //  作品描述
    NSString *imageUrl;
    NSString *wid;
    NSString *hei;
    
}
@property (nonatomic, strong) UITableView *tabelView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) IGCircleprogress *circle;
@end

@implementation BatchUploadVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeProduct];
//    self.title = @"上传私密作品";
    self.title = NSLocalizedString(@"Upload Private Works", nil);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange:) name:UITextViewTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedImageDelNotification:) name:@"selectedImageDelNotification" object:nil];
    [self creatTabelView];
    imageUrl = @"";
}

- (void)creatTabelView
{
    self.tabelView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tabelView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    _tabelView.backgroundColor = [UIColor mainBackgroundColor];
    _tabelView.estimatedRowHeight = 0;
    _tabelView.estimatedSectionHeaderHeight = 0;
    _tabelView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_tabelView];
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 90)];
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    sure.layer.cornerRadius = 20;
    sure.layer.masksToBounds = YES;
    sure.backgroundColor = [UIColor appColor];
    sure.frame = CGRectMake(0, 15, KSCALE(1100), 45);
    sure.titleLabel.font = [UIFont systemFontOfSize:16];
    [sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [sure setTitle:@"提 交" forState:UIControlStateNormal];
    [sure setTitle:NSLocalizedString(@"Submit", nil) forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    sure.centerX = footer.width/2;
    [footer addSubview:sure];
    _tabelView.tableFooterView = footer;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        CGFloat height = [self getCellItemWidth];
        int rows = (int)(_images.count/4) + 1;
        if (_images.count == 8)
        {
            rows --;
        }
        CGFloat zHeight = rows * (height + lineSpaceWidthImage) + lineSpaceWidthImage;
        return zHeight + 20;
    } else if (indexPath.row == 1) {
        return 50;
    }
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.textLabel.textColor = [UIColor c4Color];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:16];
    cell.detailTextLabel.textAlignment = NSTextAlignmentRight;
    cell.detailTextLabel.textColor = [UIColor c5Color];
    CGFloat x = cell.separatorInset.left;
    if (indexPath.row == 0)
    {
        [cell addSubview:self.collectionView];
        cell.backgroundColor = [UIColor c2Color];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(10);
            make.right.mas_equalTo(-10);
            make.top.mas_equalTo(10);
            make.bottom.mas_equalTo(-10);
        }];
    }
    if (indexPath.row == 1)
    {
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
//        field.placeholder = @"作品名(必填)";
        NSString *workName = NSLocalizedString(@"Works' Name", nil);
        NSString *rString = NSLocalizedString(@"Required", nil);
        field.placeholder = [NSString stringWithFormat:@"%@(%@)",workName,rString];
        field.textColor = [UIColor c5Color];
        field.text = publicName;
        field.textAlignment = NSTextAlignmentLeft;
        field.borderStyle = UITextBorderStyleNone;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        field.font = cell.textLabel.font;
        field.tag = nameTag;
        [field addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
        [cell.contentView addSubview:field];
    }
    else if (indexPath.row == 2)
    {
        IWTextView *field = [[IWTextView alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 95)];
        field.textColor = [UIColor c5Color];
//        field.placeholder = @"描述一下你的作品(必填)";
        NSString *describeWork = NSLocalizedString(@"Describe Your Works", nil);
        NSString *rString = NSLocalizedString(@"Required", nil);
        field.placeholder = [NSString stringWithFormat:@"%@(%@)",describeWork,rString];
        field.text = publicContext;
        field.tag = contextTag;
        field.font = cell.textLabel.font;
        [cell.contentView addSubview:field];
    }
    return cell;
}

#pragma mark ====== collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.images.count < 8)
    {
        return self.images.count + 1;
    }
    return self.images.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionViewLayout;
    CGFloat width = (self.collectionView.width - flowLayout.minimumLineSpacing * 3) / 4;
    return CGSizeMake(width, width);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGIssueImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"IGIssueImageCell" forIndexPath:indexPath];
    if (self.images.count < 8)
    {
        if (indexPath.item == self.images.count)
        {
            cell.imageView.image = [UIImage imageNamed:@"upload_image"];
        }
        else
        {
            cell.imageView.image = self.images[indexPath.item];
        }
    }
    else
    {
        cell.imageView.image = self.images[indexPath.item];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    if (indexPath.row == self.images.count) {
        __weak typeof(self) weakSelf = self;
        [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
            [IGTakePhotosUtil ig_showImagePickerControllerWithImagePickerBlock:^ (NSDictionary<NSString *,id> * _Nullable info){
                if (info) {
                    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
                    image = [image fixOrientation];
                    [weakSelf.images addObjectsFromArray:@[image]];
                    [weakSelf.assets addObjectsFromArray:@[image]];
                    [weakSelf reloadView];
                }
            }];
        } photoBlock:^{
            int maximumNumberOfSelection = (int)(8 - weakSelf.images.count);
            [IGTakePhotosUtil ig_showAssetsForProductPickerControllerWithMaximumNumberOfSelection:maximumNumberOfSelection assetsPickerBlock:^(NSArray<UIImage *> * _Nullable photos, NSArray * _Nullable assets) {
                if (assets.count != 0) {
                    [weakSelf.images addObjectsFromArray:photos];
                    [weakSelf.assets addObjectsFromArray:assets];
                    [weakSelf reloadView];
                }
            }];
        }];
    }
}

- (void)reloadView
{
    [self.tabelView reloadData];
    [self.collectionView reloadData];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = lineSpaceWidthImage;
        flowLayout.minimumInteritemSpacing = lineSpaceWidthImage;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[IGIssueImageCell class] forCellWithReuseIdentifier:@"IGIssueImageCell"];
    }
    return _collectionView;
}

- (void)textChange:(UITextField *)textField
{
    if (textField.tag == nameTag)
    {
        publicName = textField.text;
    }
}

- (void)textViewChange:(NSNotification *)not
{
    UITextView *textView = not.object;
    if ([textView isMemberOfClass:[IWTextView class]])
    {
        if (textView.tag == contextTag)
        {
            publicContext = textView.text;
        }
    }
}

#pragma mark — 上传作品

- (void)sureAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    if (publicName.length==0)
    {
//        [self presentMessageTips:@"请输入作品名称"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Works Name", nil)];

        return;
    }
    if ([Tool convertToByte:publicName] >= 20)
    {
//        [self presentMessageTips:@"作品名称过长"];
        [self presentMessageTips:@"Works Name Overlong"];
        return;
    }
    if (publicContext.length==0)
    {
//        [self presentMessageTips:@"请输入作品描述"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Works Description", nil)];
        return;
    }
    if ([Tool convertToByte:publicContext] >= 200)
    {
//        [self presentMessageTips:@"作品描述过长"];
        [self presentMessageTips:NSLocalizedString(@"Works Description Too Long", nil)];

        return;
    }
#pragma mark === 上传
    [self uploadMainImageData];
}

- (void)uploadMainImageData
{
    NSArray *uploadArr = self.images;//拍照上传的直接传image
    if(self.assets.count > 0) { //相册选择的的传assets,用于获取图片原始data
        uploadArr = self.assets;
    }
//    [self.view addSubview:self.circle];
//    [self showText:@"正在上传图片..."];
    [self showText:NSLocalizedString(@"Uploading Picture...", nil)];
    @KWeakObj(self)
    [[IGOSSManager sharedManager] asyncPutImages:uploadArr withCompleteBlock:^(NSArray *params, NSArray *urls) {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [selfWeak resetCircle];
            [self dismissLoading];
        });
//        [selfWeak showText:@"正在提交..."];
        [selfWeak showText:NSLocalizedString(@"Submitting", nil)];
        if (params.count != 0)
        {
            for (int i = 0; i < params.count; i++)
            {
                UIImage *img = _images[i];
                if ([imageUrl isEqualToString:@""])
                {
                    imageUrl = params[i];
                    wid = [NSString stringWithFormat:@"%f", img.size.width];
                    hei = [NSString stringWithFormat:@"%f", img.size.height];
                }
                else
                {
                    imageUrl = [imageUrl stringByAppendingString:[NSString stringWithFormat:@",%@",  params[i]]];
                    wid = [wid stringByAppendingString:[NSString stringWithFormat:@",%f", img.size.width]];
                    hei = [hei stringByAppendingString:[NSString stringWithFormat:@",%f", img.size.height]];
                }
            }
            [selfWeak uploadData];
        }
        else
        {
//            [selfWeak presentMessageTips:@"提交失败!"];
            [selfWeak presentMessageTips:NSLocalizedString(@"Submitting Failed!", nil)];
        }
    } progressBlock:^(CGFloat progress, int index) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"index====>%@ progress====>%@ ", @(index), @(progress));
//            selfWeak.circle.progress = progress;
//            if (progress >= 1) {
//                [selfWeak resetCircle];
//            }
        });
    } isProduct:YES];
}
- (void)uploadData
{
    @KWeakObj(self)
    IGUpProductionApi *api = [IGUpProductionApi new];
    api.title = publicName;
    api.content = publicContext;
    api.plates = @"3";
    api.isOpen = NO;
    api.image = imageUrl;
    api.cropUrl = @"";
    api.width = wid;
    api.height = hei;
    [api startWithDecodeClass:[IGUpProductionResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
//            [selfWeak presentMessageTips:@"提交成功!"];
//            [selfWeak presentMessageTips:NSLocalizedString(@"Report successfully!", nil)];
            [selfWeak presentMessageTips:NSLocalizedString(@"works upload successfully", nil)];
            NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
            for (UIViewController *vc in marr) {
                if ([vc isKindOfClass:[ArtGalleryViewController class]]) {
                    [marr removeObject:vc];
                    break;
                }
            }
            self.navigationController.viewControllers = marr;
            ArtGalleryViewController *artVC = [[ArtGalleryViewController alloc] init];
            artVC.index = 0;
            [UIViewController ig_pushViewController:artVC animated:YES];
            NSArray *currentVC = self.navigationController.viewControllers;
            NSMutableArray *allVC = [NSMutableArray arrayWithArray:currentVC];
            for (UIViewController *vc in currentVC)
            {
                if ([vc isKindOfClass:[BatchUploadVC class]])
                {
                    [allVC removeObject:vc];
                }
            }
            self.navigationController.viewControllers = allVC;
        } else
        {
//            [selfWeak presentMessageTips:@"提交失败!"];
            [selfWeak presentMessageTips:NSLocalizedString(@"Submitting Failed!", nil)];
        }
    }];
}



- (void)selectedImageDelNotification:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    [_images removeAllObjects];
    [_images addObjectsFromArray:[userInfo objectForKey:@"assets"]];
    [self reloadView];
}

- (CGFloat)getCellItemWidth
{
    return (KSCREENWIDTH - 20 - lineSpaceWidthImage * 3)/4;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (IGCircleprogress *)circle {
    if (!_circle) {
        _circle = [[IGCircleprogress alloc] init];
        _circle.progress = 0.0;
    }
    return _circle;
}

- (void)resetCircle {
    [self.circle removeFromSuperview];
    self.circle = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

